// @ 516
// _(:з」∠)_

define([
    
], function() {
    'use strict';

    let gridHeatMap = {
        loader: null,
        initGrid: function( result, type ) {
            let _this = this,
                gridLatLng = [],
                gridArry = [];

            // 移除现有图层
            _this.removeGrid( MC.map._layers );

            // 实例化标题
            Title.topTitle({
                main: result.maintile,
                sub: result.subtile
            });

            // 转移数据
            for ( let x = 0; x < result.grid.length; x++ ) {
                for ( let y = 0; y < result.grid[x].length; y++ ) {
                    gridArry.push( result.grid[x][y] );
                    gridLatLng.push([
                        ( Number( result.top ) + x * Number( result.deltaY ) ) - Number( result.deltaY ) / 2,
                        ( Number( result.left ) + y * Number( result.deltaX ) ) - Number( result.deltaX ) / 2
                    ]);
                }
            }

            // 过滤不同颜色数组
            let color = [], colorx = [], grid = [];
            
            if ( type ) {
                color = colorMatch[ type ];

                for ( let x = 0; x < color.length; x++ ) {
                    grid[x] = [];
                    for ( let y = 0; y < gridArry.length; y++ ) {
                        if ( gridArry[y] < color[x].end && gridArry[y] >= color[x].start ) {
                            grid[x].push( gridLatLng[y] );
                        }
                    }
                }

                Legend.elmt( color );
            } else {
                Popup.tipPopup({
                    type: "toast",
                    content: "未找到相应色标"
                });
            }

            // 实例化加载
            for ( let x = 0; x < grid.length; x++ ) {
                if ( grid[x].length > 0 ) {
                    _this.initLoader({
                        name: "grid_"+color[x].start,
                        deltaX: Number( result.deltaX ),
                        deltaY: Number( result.deltaY ),
                        grid: grid[x],
                        img: Path + '/script/extend/colorMatching/'+ type +'/grid_'+ color[x].start +'.png'
                    });
                }
            }
        },
        initLoader: function( param ) {
            let _this = this;

            _this.loader = new PIXI.loaders.Loader();
            _this.loader.add( param.name, param.img );

            _this.loader.load( function( loader, resources ) {
                var texture = resources[ param.name ].texture;

                var pixiLayer = (function() {
                    var zoomChangeTs = null,
                        pixiContainer = new PIXI.Container(),
                        innerContainer = new PIXI.particles.ParticleContainer(
                            param.grid.length, {
                                vertices: true
                            }
                        );
    
                    innerContainer.texture = texture;
                    innerContainer.baseTexture = texture.baseTexture;
                    innerContainer.anchor = { x: 0, y: 0 };
    
                    pixiContainer.addChild( innerContainer );
                    var initialScale;
                    
                    return L.pixiOverlay( function( utils, event ) {
                        let zoom = utils.getMap().getZoom(),
                            container = utils.getContainer(),
                            renderer = utils.getRenderer(),
                            project = utils.latLngToLayerPoint,
                            getScale = utils.getScale,
                            invScale = 1 / getScale();
        
                        if ( event.type === 'add' ) {
                            initialScale = invScale / 8;
                            innerContainer.localScale = initialScale;
        
                            for ( let x = 0; x < param.grid.length; x++ ) {
                                let cust = MC.customCRS.unproject(
                                        L.point(
                                            ( param.grid[x][1] + param.deltaY / 2 ),
                                            ( param.grid[x][0] + param.deltaX / 2 )
                                        )
                                    ),
                                    cust_ = MC.customCRS.unproject(
                                        L.point(
                                            ( param.grid[x][1] - param.deltaY / 2 ),
                                            ( param.grid[x][0] - param.deltaX / 2 )
                                        )
                                    ),
                                    coord = project([ cust.lng, cust.lat ]),
                                    coord_ = project([ cust_.lng, cust_.lat ]),
                                    origin = MC.customCRS.unproject(
                                        L.point( param.grid[x][1], param.grid[x][0] )
                                    ),
                                    origin_ = project([ origin.lat, origin.lng ]),
                                    width = ( coord.x - coord_.x ), height = ( coord_.y - coord.y );
                                
                                let scalex = MC.map.getZoom() / initialScale,
                                    widthx = width * scalex / 4 + 1, heightx = height * scalex / 4 + 1;
                            
                                innerContainer.texture.orig.width = widthx;
                                innerContainer.texture.orig.height = heightx;
                                innerContainer.texture._frame.width = widthx;
                                innerContainer.texture._frame.height = heightx;
                                innerContainer.texture.baseTexture.width = widthx;
                                innerContainer.texture.baseTexture.height = heightx;
                                innerContainer.texture.baseTexture.realWidth = widthx;
                                innerContainer.texture.baseTexture.realHeight = heightx;
                                innerContainer.baseTexture = innerContainer.texture.baseTexture;

                                innerContainer.addChild({
                                    x: origin_.x,
                                    y: origin_.y,
                                    width: widthx,
                                    height: heightx
                                });
                            }
                        }
        
                        if ( event.type === 'zoomanim' ) {
                        	var targetZoom = event.zoom;
                        	if ( targetZoom >= 1 || zoom >= 1 ) {
                        		zoomChangeTs = 0;
                        		var targetScale = targetZoom >= 1 ? 1 / getScale(event.zoom) : initialScale;
                        		innerContainer.currentScale = innerContainer.localScale;
                        		innerContainer.targetScale = targetScale;
                        	}
                        	return;
                        }
        
                        if ( event.type === 'redraw' ) {
                        	var delta = event.delta;
                        	if (zoomChangeTs !== null) {
                        		var duration = 17;
                        		zoomChangeTs += delta;
                        		var lambda = zoomChangeTs / duration;
                        	    if ( lambda > 1 ) {
                        	  	    lambda = 1;
                        	  	    zoomChangeTs = null;
                        	    }
                        	    lambda = easing( lambda );
                        	    innerContainer.localScale = innerContainer.currentScale + lambda * (innerContainer.targetScale - innerContainer.currentScale);
                        	} else { return; }
                        }
        
                        renderer.render( container );
                    }, pixiContainer );
                })();
    
                pixiLayer.addTo( MC.map );
    
                var ticker = new PIXI.ticker.Ticker();
                ticker.add(function(delta) {
                	pixiLayer.redraw({type: 'redraw', delta: delta});
                });
                MC.map.on('zoomanim', pixiLayer.redraw, pixiLayer);
            });
        },
        isItExists: function( layers ) {
            let _this = this,
                layerArry = [];

            for ( let x in layers ) {
                if ( layers[x]._container ) {
                    if ( layers[x]._container.hasClass("leaflet-pixi-overlay") ) {
                        layerArry.push( layers[x] );
                    }
                }
            }

            if ( layerArry.length > 0 ) {
                return true;
            } else {
                return false;
            }
        },
        removeGrid: function( layers ) {
            let _this = this,
                layerArry = [];

            if ( _this.loader ) {
                _this.loader.destroy();
                _this.loader = null;
            }

            for ( let x in layers ) {
                if ( layers[x]._container ) {
                    if ( layers[x]._container.hasClass("leaflet-pixi-overlay") ) {
                        layerArry.push( layers[x] );
                    }
                }
            }

            if ( layerArry.length > 0 ) {
                for ( let x = layerArry.length - 1; x >= 0; x-- ) {
                    MC.map.removeLayer( layerArry[x] );
                }
            }
        }
    }

    window.gridHeatMap = gridHeatMap;

    return gridHeatMap;
});